import uma from 'umtrack-wx';
import { Component } from 'react';
import Taro from '@tarojs/taro';
import 'taro-skeleton/dist/index.css'
import {Provider} from 'react-redux'
import configStore from './store'
import {user} from './utils/user.service'
import {platform} from './utils/platform-settting.service';
import {getStorageSync, setStorageSync} from './utils/tools';
import {BASE_URL, PAY_MP_LOGIN} from './constants/api';
import {http} from "./utils/http";
import './app.scss'

let VConsole
if (process.env.TARO_ENV === 'h5') {
  VConsole = require('vconsole')
}

const store = configStore()

class App extends Component {

  constructor() {
    super();
    if (process.env.TARO_ENV === 'tt') {
      tt.onUnhandledRejection((e) => {
        if (e && e.reason && e.reason.errMsg && e.reason.errMsg.endsWith('is not in app.json')) {
          Taro.showModal({
            title: '',
            content: '暂不支持，敬请期待',
            showCancel: false
          })
        }
      })
    }
  }

  globalData = {
    canShowPayButton: process.env.TARO_ENV === 'tt' ? tt.canIUse('microapp-trade-plugin') : false,
    canShowConsumeCard: process.env.TARO_ENV === 'tt' ? tt.canIUse('consume-card') : false
  }

  async UNSAFE_componentWillMount() {
    const isH5 = process.env.TARO_ENV === 'h5'
    if (isH5) {
      setStorageSync('href', window.location.href)
    }
    const data: any = {
      mainColor: process.env.mainColor, // 主色调
      auxiliaryColor: process.env.auxiliaryColor,  // 辅色
      priceColor: '#ff3e01',  // 价格色
      originalPriceColor: '#969696', // 原价色
      discountBgColor: '#ff3e01', // 折扣底色
      titleColor: '#ff601b', // 标签边框颜色和文字颜色
    }
    if (data.auxiliaryColor) {
      // 有辅色
      const {mainColor, auxiliaryColor} = data;
      data.gradientColor = `linear-gradient(90deg, ${mainColor}, ${auxiliaryColor})`; // 渐变色
    } else {
      data.gradientColor = data.mainColor;
    }
    setStorageSync('colorData', data);
    if (isH5 && getStorageSync('onlyTicketPay') && ['/distributor/meals/detail', '/main/order/confirm', '/other/agreement/service', '/other/agreement/lineService', '/other/meal/index',].indexOf(document.location.pathname) <= -1) {
      Taro.clearStorageSync()
    }
    if (getStorageSync('openDebug')) {
      new VConsole()
    }
    if (isH5) {
      // 如果不是h5支付页面
      if (document.location.pathname != '/pay/index' && document.location.pathname != '/pay/success') {
        const login = await user.checkLogin()
        if (!login && process.env.P_ENV === 'lx') { // 如果没有登录，lx平台跳转去登录
          await user.jumpLogin()
          return false
        }
      } else {
        return false
      }
    }
    await platform.getSupport()
    await platform.getSetting()
  }

  async componentDidMount() {
    const compileEnv = process.env.TARO_ENV
    if (compileEnv === 'tt') {
      Taro.getApp().getPhoneNumber = async function getPhoneNumber({params, success}) {
        let phoneNumber = getStorageSync('localPhone')
        if (!phoneNumber) {
          const randomUuid = getStorageSync('randomUuid')
          const {iv, encryptedData} = params
          const data = {iv, encryptedData}
          const ret = await http.carGet(`msvc-shop/v2/bytedance/user/phone/` + randomUuid, data)
          if (ret) {
            phoneNumber = JSON.parse(ret).phoneNumber || ''
            setStorageSync('localPhone', phoneNumber)
          }
        }
        // 回调交易模版
        success({phoneNumber})
      }
    }
    const param: { [key: string]: any } = Taro.getCurrentInstance().router.params
    if (compileEnv === 'weapp') {
      if (process.env.NODE_ENV === 'production') {
        uma.init({
          appKey: '6120664d10c4020b03e70436',
          useOpenid: false,
          autoGetOpenid: false,
          debug: false
        })
      }
      if (param.scene) {
        const scene = param && (param.scene || '')
        if (scene && typeof (scene) == 'string') {
          const sellerInfo = scene.split('_')
          user.bindSellerId = Number(sellerInfo[1]) || 0
          setStorageSync('bindSellerId', user.bindSellerId)
        }
      }
    }
    if (param && param.bindSellerId) {
      user.bindSellerId = Number(param.bindSellerId) || 0
      setStorageSync('bindSellerId', user.bindSellerId)
    }
    if (compileEnv === 'h5') {
      const pathname = document.location.pathname
      //如果不是h5支付页面
      if (pathname === '/pay/index') {
        const search = Taro.getCurrentInstance().router.params
        if (search) {
          if (!search.uuid) {
            window.location.href = BASE_URL + PAY_MP_LOGIN + document.location.search + '&referer=' + document.location.href.split('?')[0]
          }
        } else {
          window.location.href = '/other/error/index'
        }
      }
    }
  }

  async componentDidCatchError(err) {
    console.error('err', err)
  }

  componentDidShow() {
    if (process.env.TARO_ENV === 'tt' && !tt.canIUse('consume-card')) {
      Taro.showModal({
        title: '',
        content: '您的抖音版本过低，请前往应用商店升级',
        showCancel: false,
        success: () => {
          tt.exitMiniProgram()
        }
      })
    }
  }

  render() {
    return (
      // eslint-disable-next-line react/react-in-jsx-scope
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}

export default App;
